package com.example.kotlineventtracker

import android.os.Bundle
import android.widget.EditText
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.kotlineventtracker.databinding.ActivityMainBinding
import com.example.kotlineventtracker.viewmodel.EventViewModel
import com.example.kotlineventtracker.util.EventRepository
import com.example.kotlineventtracker.view.EventAdapter

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 显示弹窗要求用户输入 token
        showTokenDialog()
    }

    // 显示输入 token 的弹窗
    private fun showTokenDialog() {
        val editText = EditText(this)  // 创建一个 EditText 组件供用户输入 token
        val dialog = AlertDialog.Builder(this)
            .setTitle("请输入 Token")
            .setMessage("请输入您的 token 来继续访问。")
            .setView(editText)  // 把 EditText 作为视图传给对话框
            .setPositiveButton("确定") { dialogInterface, _ ->
                val token = editText.text.toString()
                if (token.isNotEmpty()) {
                    // 设置 token 到单例的 EventRepository
                    val eventRepository = EventRepository.getInstance(applicationContext)
                    eventRepository.setToken(token)
                    // 在用户输入 token 后，初始化视图
                    initializeView()
                } else {
                    showToast("Token 不能为空！")
                    showTokenDialog()
                }
                dialogInterface.dismiss()  // 关闭对话框
            }
            .setNegativeButton("取消") { dialogInterface, _ ->
                dialogInterface.dismiss()  // 关闭对话框
            }
            .create()

        dialog.show()
    }

    // 初始化视图
    private fun initializeView() {
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.recyclerView.layoutManager = LinearLayoutManager(this)

        val viewModel: EventViewModel by viewModels()

////        // 通过单例获取 repository
//        val eventRepository = EventRepository.getInstance(applicationContext)
//        // 设置 repository
//        viewModel.setRepository(eventRepository)
        viewModel.loadEvents("page", "")
        viewModel.events.observe(this, Observer { events ->
            binding.recyclerView.adapter = EventAdapter(events, "page")
        })
    }

    // 显示 Toast 提示
    private fun showToast(message: String) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }
}


